require("task")

util = {
	pwd = function()
		if util.PWD ~= nil then return util.PWD end
		local stdout = task.executer("pwd")
		local ret = (stdout:lines())()
		stdout:close()
		util.PWD = ret
		return ret
	end,
	
	sleep = function(seconds)
		task.execute("sleep", seconds)
	end,
	
	find = function(path, _type, follow, handler)
		local typeSwitch, typeValue
		if _type then
			typeSwitch = "-type"
			typeValue = _type
		end
		local followSwitch
		if follow then followSwitch = "-L" end
		local f = task.executer("find", followSwitch, path, typeSwitch, typeValue)
		for line in f:lines() do
			handler(line)
		end
		f:close()
	end,
	
	mount = function(paths, on)
		if paths == nil then return end
		if on then
			command = "mount"
		else
			command = "umount"
		end
		if type(paths) == "string" then
			return task.execute(command, paths)
		else
			local ret = 0
			for k, path in pairs(paths) do
				local err = task.execute(command, path)
				if err ~= 0 then ret = ret + 1 end
			end
			return ret
		end
	end,
	
	mkdir = function(path)
		return task.execute("mkdir", "-p", path)
	end,
	
	exists = function(path)
		local f = io.open(path, "r")
		local ret = (f ~= nil)
		if f then f:close() end
		return ret
	end,
	
	mkfifo = function(path)
		return task.execute("mkfifo", path)
	end,
	
	cp = function(src, dst)
		local sf = io.open(src, "r")
		if sf == nil then
			log("util", "Cannot open source file %q", src)
			return false
		end
		local df = io.open(dst, "w")
		if df == nil then
			log("util", "Cannot open destination file %q", dst)
			sf:close()
			return false
		end
		local size = 1024
		local buffer
		repeat
			buffer = sf:read(size)
			if buffer then df:write(buffer) end
		until buffer == nil
		sf:close()
		df:flush()
		df:close()
		return true
	end,
	
	pgrep = function(pattern)
		local user = os.getenv("USER")
		assert(user, "Variable USER not set")
		local pids = {}
		task.executerh(function(line)
			pids[#pids + 1] = tonumber(line)
		end, "pgrep", "-U", user, pattern)
		return pids
	end,
	
	sound = function(name, bg)
		local path = string.format("%s/%s.wav", common.getConfig("path.sounddir"), name)
		if bg then
			return task.executebg("aplay", path) == 0
		else
			return task.execute("aplay", path) == 0
		end
	end
}


